// pages/store/storeSearch/storeSearch.js
import utils from "../../../utils/utils";
import Data from "../../../utils/data";
import {
  StoreHttp
} from '../../../api/store.js'
import {
  KeywordHttp
} from '../../../api/keyword.js'
import {
  CartHttp
} from '../../../api/cart.js'
import {
  storeInfoMap,
  storeGoodsListMap,
  storeGoodsDetailsMap,
  cartListMap,
  cartDiscountsMap,
  cartRecommendGoodMap
} from '../../../utils/dataMap.js'

const storeModel = new StoreHttp();
const keywordModel = new KeywordHttp();
const cartModel = new CartHttp();
const app = getApp()


Page({
  data: {
    goodsId: 0, // 商品Id
    storeId: 0, // 店铺Id
    storeInfo: {}, // 店铺信息
    serviceId: 0, // 服务站Id
    isStoreOpen: true, // 店铺是否营业

    cartDiscountsInfo: {}, // 购物车 - 购物车计算优惠信息
    cartList: [], // 购物车 - 购物车列表
    needGoodsList: [], // 购物车 - 配套商品列表
    isClearingBtnClick: false, // 结算按钮是否点击
    isShowCartAlertParent: true, // 是否控制显示购车提示
    isShowCartAlert: false, // 是否显示购物车提示
    isShowGoodsSkuPopup: false, // 是否显示商品规格弹窗

    searchKeyword: '', // 搜索关键词
    searchHistory: [], // 搜索历史
    goodsList: [], // 搜索结果
    isShowSearchHistory: true, // 是否显示搜索历史
    isShowSearchResult: false, // 是否显示搜索结果
    page: 1,
    pageSize: 10,
    totalNum: 0,
    initUser: true,
    openLogin: false,
  },

  // 页面载入完成
  initPage: function (options) {
    this.setData({
      storeId: options.storeId,
      serviceId: options.serviceId,
      searchHistory: keywordModel.getHistory('search_store_goods_history')
    })
    this.httpGetStoreInfo(options.storeId) // 获取店铺信息
    if (this.data.userInfo && this.data.userInfo.uid) {
      this.httpGetCartList() // 请求店铺购物车
    }
  },

  //清除历史
  onClearHistory: function () {
    this.setData({
      searchHistory: [],
    });
    wx.setStorageSync('search_store_goods_history', [])
  },

  // 搜索框 - 输入内容变化时触发
  onChange: function (e) {
    this.setData({
      searchKeyword: e.detail
    });
  },

  // 搜索框 - 点击清空控件时触发
  onSearchClear () {
    this.setData({
      searchVal: '',
      isShowSearchHistory: true,
      isShowSearchResult: false
    })
  },

  // 搜索框 - 确定搜索时触发
  onSearch: function (event) {
    const { searchKeyword } = this.data
    const { value } = event.currentTarget.dataset
    let searchVal = value || searchKeyword
    if (searchVal === '') {
      utils.msg('请输入关键词!');
      return false;
    }
    keywordModel.addToHistory('search_store_goods_history', searchVal)
    this.setData({
      page: 1,
      searchKeyword: searchVal,
      isShowSearchHistory: false,
      searchHistory: keywordModel.getHistory('search_store_goods_history')
    })
    this.httpGetGoodsList()
  },

  // scroll-view 页上拉触底事件的处理函数
  onScrollToLower () {
    const { goodsList, page, totalNum } = this.data
    if (goodsList.length < totalNum) {
      this.setData({
        page: page + 1
      })
      this.httpGetGoodsList()
    }
  },

  // 购物栏 - 结算
  onClearingCart() {
    const { cartList, storeId, needGoodsList, isClearingBtnClick } = this.data;
    let serviceCenterId = this.data.storeInfo.serviceCenterId;
    const navToClearing = function () {
      let cartListArr = cartList
        // .filter(item => item.stockStatus === 1 || item.stockStatus === 2)
        .map((item) => {
          return {
            cart_id: item.cartId,
            sku_id: item.goodsSkuId,
            spu_id: item.goodsSpuId,
            amount: item.currentNum,
          }
        });
      wx.navigateTo({
        url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}`
      })
    };
    if (cartList.length === 0) return
    if (needGoodsList.length !== 0) {
      if (isClearingBtnClick) {
        navToClearing()
      } else {
        this.setData({
          isShowCartAlert: true,
          isClearingBtnClick: true
        })
      }
    } else {
      navToClearing()
    }
  },

  // 购物栏提示 - 取消
  onCartAlertCancel () {
    this.setData({
      isShowCartAlertParent: false
    })
  },

  // 购物栏提示 - 确定
  onCartAlertConfirm() {
    const { needGoodsList, storeId } = this.data
    let addCartGoodsInfo = needGoodsList.map(item => {
      return {
        goodsThumbnailUrl: item.goodsImg,
        goodsTitle: item.goodsName,
        skuId: item.goodsSkuId,
        spuId: item.goodsSpuId,
        skuAmount: 1
      }
    })
    let addCartInfo = {
      goods: addCartGoodsInfo,
      storeId: this.data.storeId,
      userId: this.data.userInfo.uid
    }
    this.httpAddCartGoods(addCartInfo).then(() => {
      this.setData({
        needGoodsList: [],
        isShowCartAlert: false
      })
    })
  },

  // 添加到购物车 - 单规格商品
  onAddCart(event) {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      this.setData({
        openLogin: true,
        initUser: false
      })
      return 
    }
    app.event.emit('addCartAnimation', event.detail.pos)
    const { goods } = event.detail
    let addCartInfo = {
      goods: [{
        goodsThumbnailUrl: goods.goodsThumbnailImg,
        goodsTitle: goods.goodsName,
        skuId: goods.singleSku.goods_sku_id,
        spuId: goods.goodsId,
        skuAmount: 1,
      }],
      storeId: goods.storeId,
      userId: this.data.userInfo.uid
    }
    this.httpAddCartGoods(addCartInfo);
  },

  // 选择商品规格 - 多规格商品
  onSelectSku(event) {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      this.setData({
        openLogin: true,
        initUser: false
      })
      return 
    }
    this.AnimationData = event.detail.Animation;
    const { goods } = event.detail;
    this.setData({
      multiSkuGoodsInfo: goods,
      isShowGoodsSkuPopup: true
    })
  },

  // 选择商品规格 - 加入购物车
  onSkuAddCart (event) {
    const { storeInfo } = this.data
    if (storeInfo.cooperationType === 1) {
      // 自营商品 - 加入购物车
      let addCartInfo = {
        goods: [event.detail],
        storeId: this.data.storeId,
        userId: this.data.userInfo.uid
      }
      this.httpAddCartGoods(addCartInfo).then((res) => {
        this.setData({
          isShowGoodsSkuPopup: false
        })
      });
    } else {
      // 1688 - 立即购买
      const { storeId, serviceCenterId } = this.data.storeInfo
      let cartListArr = [{
        // cart_id: item.cartId,
        sku_id: event.detail.skuId,
        spu_id: event.detail.spuId,
        amount: event.detail.skuAmount,
      }]
      wx.navigateTo({
        url: `/pages/goods/pendingOrder/pendingOrder?id=${JSON.stringify(cartListArr)}&storeId=${storeId}&serviceId=${serviceCenterId}&type=3`
      })
    }
  },

  // 选择商品规格 - 关闭商品规格弹出层
  onCloseSkuPopup () {
    this.setData({
      isShowGoodsSkuPopup: false
    })
  },

  // 清空购物车
  onClearCartList() {
    storeModel.deleteCartGoods({
      store_id: this.data.storeId
    }).then((res) => {
      // this.setData({
      //   isShowCartAlert: false,
      //   isClearingBtnClick: false
      // })
      this.httpGetCartList()
    })
  },

  // 修改购物车商品数量
  onChangeStepper (event) {
    const { goods } = event.detail
    storeModel.addGoodsNumToStoreCart({
      goods: [goods],
      storeId: this.data.storeId,
      userId: this.data.userInfo.uid
    }).then((res) => {
      this.httpGetCartList()
    })
  },

  // 添加到购物车
  httpAddCartGoods (param) {
    return storeModel.addGoodsToStoreCart(param).then((res) => {
      //utils.msg('已加入购物车！')
      this.httpGetCartList()
    }).catch((err) => {
      if (err.code === 2007) {
        utils.msg('请登录后操作！')
      }
    })
  },

  // 获取购物车列表
  httpGetCartList () {
    return storeModel.getStoreCartList({
      storeId: this.data.storeId,
      userId: this.data.userInfo.uid
    }).then((res) => {
      if (!res.skuList || (res.skuList && res.skuList.length === 0)) {
        this.setData({
          cartDiscountsInfo: cartDiscountsMap(res),
          cartList: res.skuList ? cartListMap(res.skuList) : [],
          needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : [],
          isShowCartAlert: false,
          isClearingBtnClick: false
        })
      } else {
        this.setData({
          cartDiscountsInfo: cartDiscountsMap(res),
          cartList: res.skuList ? cartListMap(res.skuList) : [],
          needGoodsList: res.cartRecommendGoods ? cartRecommendGoodMap(res.cartRecommendGoods) : []
        })
      }
    })
  },

  // 获取商品列表
  httpGetGoodsList () {
    const { storeId, searchKeyword, goodsList, page, pageSize } = this.data
    storeModel.getGoodsList({
      page: page,
      page_size: pageSize,
      store_id: storeId,
      goods_title: searchKeyword,
    }).then((res) => {
      let resMap = storeGoodsListMap(res.goods_list)
      let goodsListArr = page === 1 ? resMap : goodsList.concat(resMap)
      this.setData({
        goodsList: goodsListArr,
        isShowSearchHistory: false,
        isShowSearchResult: true,
        totalNum: res.total_count
      })
    })
  },

  // 获取店铺信息
  httpGetStoreInfo(id) {
    const {
      longitude,
      latitude
    } = this.data
    return storeModel.getStoreInfo({
      "lng": longitude || 0, // 经度
      "lat": latitude || 0, // 纬度
      "store_id": id
    }).then((res) => {
      const { store_info } = res
      wx.setNavigationBarTitle({
        title: store_info.store_info
      });
      let info = storeInfoMap(store_info)
      this.setData({
        isStoreOpen: info.isOpening,
        storeInfo: info
      })
    })
  }
});
